package cn.com.customer.manager.ui.task.list

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.com.customer.manager.Constants
import cn.com.customer.manager.R
import cn.com.customer.manager.adapter.TaskListAdapter
import cn.com.customer.manager.base.BaseFragment
import cn.com.customer.manager.bean.RequestBean
import cn.com.customer.manager.bean.TaskItem
import cn.com.customer.manager.bean.TaskListRespond
import cn.com.customer.manager.http.BaseApi
import cn.com.customer.manager.http.subscriber.TipRequestSubscriber
import cn.com.customer.manager.ui.message.messageMian.MessageActivity
import cn.com.customer.manager.ui.task.TaskDetailActivity
import cn.com.customer.manager.ui.task.addTask.AddTaskActivity
import com.chad.library.adapter.base.BaseQuickAdapter
import com.codbking.calendar.CalendarDate
import com.codbking.calendar.CalendarDateView
import com.codbking.calendar.CalendarView
import com.xuexiang.xhttp2.XHttp
import com.xuexiang.xhttp2.model.ApiResult
import com.xuexiang.xui.utils.DensityUtils
import com.xuexiang.xui.utils.ThemeUtils
import com.xuexiang.xui.widget.actionbar.TitleBar
import com.xuexiang.xutil.tip.ToastUtils
import kotlinx.android.synthetic.main.fragment_task.*
import java.util.*


/**
 * 任务
 */
class TaskFragment : BaseFragment(), BaseQuickAdapter.OnItemClickListener , BaseQuickAdapter.RequestLoadMoreListener{
    private lateinit var mAdapter: TaskListAdapter
    var data = CalendarDate.get(Date())
    var pageNo=1
    var params:MutableMap<String,String> = mutableMapOf()
    var list:MutableList<TaskItem> = mutableListOf()
    lateinit var time:String
    override fun getLayoutId(): Int = R.layout.fragment_task
    override fun initView() {
        task_title.addAction(object :TitleBar.ImageAction(R.drawable.message_push){
            override fun performAction(view: View?) {
                startActivity(Intent(activity, MessageActivity::class.java))
            }

        })
        initViewData()
        initListener()
        initRv()
        requestData()
        iv_add_task.setOnClickListener{
            startActivity(Intent(activity, AddTaskActivity::class.java))
        }
    }

    private fun initViewData() {
        calendarDateView.setAdapter { convertView1: View?, parentView: ViewGroup, calendarDate: CalendarDate ->
            val textView: TextView
            var convertView: View? =null
            if (convertView == null) {
                convertView = LayoutInflater.from(parentView.context).inflate(R.layout.adapter_calendar_item, null)
                val params = ViewGroup.LayoutParams(DensityUtils.dp2px(48f), DensityUtils.dp2px(48f))
                convertView.layoutParams = params
            }
            textView = convertView!!.findViewById(R.id.tv_text)
            textView.setBackgroundResource(R.drawable.bg_calendar_material_design_item)
            textView.text = calendarDate.day.toString()
            if (calendarDate.monthFlag != 0) {
                textView.setTextColor(-0x6d665f)
            } else {
                if (calendarDate.isToday && calendarDate.equals(calendarDateView.selectCalendarDate)) {
                    textView.setTextColor(ThemeUtils.resolveColor(context, R.attr.colorAccent))
                } else {
                    textView.setTextColor(ThemeUtils.resolveColor(context, R.attr.xui_config_color_content_text))
                }
            }
            convertView
        }


//        tv_china_date.setText(ChinaDateUtils.oneDay(data.year, data.month, data.day))
        calendarDateView.setOnCalendarSelectedListener(CalendarView.OnCalendarSelectedListener { view, postion, calendarDate ->
            ToastUtils.toast("选中:" + calendarDate.formatDate())
            time=calendarDate.formatDate()
            requestData()
//            tv_china_date.setText(ChinaDateUtils.oneDay(calendarDate.year, calendarDate.month, calendarDate.day))
        })

        calendarDateView.setOnTodaySelectStatusChangedListener(CalendarView.OnTodaySelectStatusChangedListener { todayView: View, isSelected: Boolean ->
            val view = todayView.findViewById<TextView>(R.id.tv_text)
            if (isSelected) {
                view.setTextColor(ThemeUtils.resolveColor(context, R.attr.xui_config_color_content_text))
            } else {
                view.setTextColor(ThemeUtils.resolveColor(context, R.attr.colorAccent))
            }
        })
        calendarDateView.setOnMonthChangedListener(CalendarDateView.OnMonthChangedListener { view: View?, position: Int, date: CalendarDate ->
            tv_title.text = String.format("%d年%d月", date.year, date.month)
            time=date.formatDate()
            requestData()
//            tv_china_date.setText(ChinaDateUtils.oneDay(date.year, date.month, date.day))
        })

        val date = CalendarDate.get(Date())
        tv_title.text = String.format("%d年%d月", date.year, date.month)
        time=date.formatDate()
    }

    private fun initListener() {
        iv_previous.setOnClickListener {
            calendarDateView.previous()
        }
        iv_next.setOnClickListener {
            calendarDateView.next()
        }
    }
    private fun initRv() {
        rv_list.layoutManager = LinearLayoutManager(mContext, RecyclerView.VERTICAL, false)
        mAdapter = TaskListAdapter(R.layout.item_date_task)
        rv_list.adapter = mAdapter
        mAdapter.onItemClickListener = this

    }
    private fun requestData() {
        params["pageNo"]=pageNo.toString()
        params["pageSize"]="1000"
        params["taskType"]=""
        params["customerName"]=""
        params["time"]=time
        val request = XHttp.custom()
        request.call(request.create(BaseApi.ITask::class.java)
                .taskList(RequestBean(params)))
                .subscribeWith(object : TipRequestSubscriber<ApiResult<TaskListRespond>?>() {
                    override fun onSuccess(apiResult: ApiResult<TaskListRespond>?) {
                        apiResult?.let {
                            if (it.data!=null){
                                setTaskList(it.data)
                            }
                        }
                    }
                })
    }
     fun setTaskList(result: TaskListRespond) {
         list=result.notCompletedTaskList
        if (pageNo == 1) {
            mAdapter.setNewData(list)
        } else {
            mAdapter.addData(list)
        }
        if (mAdapter.isLoadMoreEnable and mAdapter.isLoading) {
            mAdapter.loadMoreComplete()
        }
        if(result.completedTaskList.size+result.notCompletedTaskList.size<Constants.PAGE_SIZE){
            mAdapter.loadMoreEnd()
        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        startActivity(Intent(activity, TaskDetailActivity::class.java).putExtra("data", list[position].taskId))
    }

    override fun onLoadMoreRequested() {
        pageNo++
        requestData()
    }
}